package cn.xianshu.org.controller;

import cn.xianshu.basic.util.AxiosResult;
import cn.xianshu.basic.util.PageList;
import cn.xianshu.org.domain.Department;
import cn.xianshu.org.query.DepartmentQuery;
import cn.xianshu.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;


    /**
     * 查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    /**
     * 查询所有数据
     * @return
     */
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.findAll();
    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryList(query);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AxiosResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AxiosResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("系统繁忙，请稍后重试...");
        }
    }

    @PatchMapping
    public AxiosResult Bydelete(@RequestBody List<Long> ids){
        try {
            departmentService.Bydelete(ids);
            return AxiosResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("系统繁忙，请稍后重试");
        }
    }

    /**
     *  添加和修改
     * @param department
     * @return
     */
    @PutMapping
    public AxiosResult addAndUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.insert(department);
            } else {
                departmentService.update(department);
            }
            return AxiosResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("系统繁忙，请稍后重试...");
        }
    }


    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}
